#-*- coding: UTF-8 -*-
# 需求：输出单个文件中的前 N 个最常出现的英语单词。

# 获取文本内容，分隔单词
def get_words(filename):
    with open(filename) as f:
        content = f.read()
        # 处理标点符号
        content = content.replace(",", "")
        content = content.replace(".", "")
        content = content.replace("!", "")
        content = content.replace("?", "")
        # 处理首尾空格
        content = content.strip()
        # 生成单词列表
        words = [word.lower() for word in content.split()]
        # print(words)
        return words
# 单词计数
def count_words(filename):
    # 获取单词列表
    words = get_words(filename)
    # 通过列表生成字典
    words_amount = dict.fromkeys(words, 0)
    # 遍历单词
    for word in words_amount.keys():
        # 计数统计
        cnt = words.count(word)
        words_amount[word] = cnt
    # 根据频数降序排序
    words_amount = sorted(words_amount.items(), key=lambda x:x[1], reverse=True)
    return words_amount
# 主函数
if __name__ == "__main__":
    N = 10
    filename = "experiment_1/text.txt"
    words_amount = count_words(filename=filename)
    # print(words_amount)
    # 遍历前N个元素取答案
    for el in words_amount[:N]:
        print('{0:<8} : {1}'.format(el[0], el[1]))